<script setup lang="ts">
import { ElMessage } from 'element-plus';

import SubViewContainer from '@core/components/subLayout/SubViewContainer.vue';
import RouteHelper from '@core/utils/RouteHelper';
import Order, { OrderParams } from '@core/engine/Order';
import * as Enums from '@firewall/engine/Enums';
import Firewall, { FirewallInstance } from '@firewall/engine/Firewall';
import OrderHelper from '@firewall/utils/OrderHelper';

const route = useRoute();
const { t } = useI18n({ inheritLocale: true, useScope: 'local' });

const price = ref(0);
const remoteValues = reactive({
  ipCount: 0,
  flowCapacity: 0,
});
const isLoading = ref(true);
const isCheckedAgree = ref(false);

const firewall: Partial<FirewallInstance> = reactive({});
const fetchFirewall = async () => {
  const response = await Firewall.fetchSummaryList({
    vpcIds: RouteHelper.queryValueToPlural(route.query.vpcId),
  });
  const remoteFirewall = response.list?.[0];
  if (!remoteFirewall) {
    return;
  }
  remoteFirewall.protectionIpNum += OrderHelper.MIN_IP_COUNT;
  remoteFirewall.flowProcessingCapacity += OrderHelper.MIN_FLOW_CAPACITY;
  Object.assign(firewall, remoteFirewall);
  remoteValues.ipCount = remoteFirewall.protectionIpNum;
  remoteValues.flowCapacity = remoteFirewall.flowProcessingCapacity;
};

const resourceIdTypeMap: Record<string, string> = {
  [Enums.OrderResourceType.Master]: '',
  [Enums.OrderResourceType.Ip]: '',
  [Enums.OrderResourceType.Bandwidth]: '',
};

const fetchResources = async () => {
  const { masterOrderId } = firewall;
  if (!masterOrderId) {
    return;
  }
  const response = await Order.queryResourcesByMaster(masterOrderId);
  response.forEach((resource) => {
    resourceIdTypeMap[resource.resourceType] = resource.resourceId;
  });
};

const isFailedToFetch = ref(false);
onMounted(async () => {
  isLoading.value = true;
  try {
    await fetchFirewall();
    await fetchResources();
  } catch (e) {
    isFailedToFetch.value = true;
  } finally {
    isLoading.value = false;
  }
});

const isUpgrading = computed(() => {
  if (!firewall.protectionIpNum || !firewall.flowProcessingCapacity) {
    return false;
  }
  return firewall.protectionIpNum > remoteValues.ipCount
    || firewall.flowProcessingCapacity > remoteValues.flowCapacity;
});
const isDegrading = computed(() => {
  if (!firewall.protectionIpNum || !firewall.flowProcessingCapacity) {
    return false;
  }
  return firewall.protectionIpNum < remoteValues.ipCount
    || firewall.flowProcessingCapacity < remoteValues.flowCapacity;
});

const getUpdateOrderParams = (): OrderParams | null => {
  return OrderHelper.buildOrderParams({
    protectionIpCount: firewall.protectionIpNum,
    flowProcessingCapacity: firewall.flowProcessingCapacity,
    resourceIdTypeMap,
  });
};

const isQueryingPrice = ref(false);
const onOrderResourceChange = async () => {
  const orderParams = getUpdateOrderParams();
  if (!orderParams) {
    return;
  }
  isQueryingPrice.value = true;
  try {
    if (isUpgrading.value) {
      const response = await Order.queryUpgradeOrderPrice({ orders: [orderParams] });
      price.value = response.totalPrice;
    } else if (isDegrading.value) {
      const response = await Order.queryDegradeOrderPrice({ orders: [orderParams] });
      price.value = response.totalPrice;
    } else {
      price.value = 0;
    }
  } finally {
    isQueryingPrice.value = false;
  }
};

const needMoreResource = ref(false);
const onSubmit = async () => {
  if (!isUpgrading.value && !isDegrading.value) {
    ElMessage.info({ message: t('noChangeBySlider') });
    return;
  }
  const { vpcId, flowProcessingCapacity, protectionIpNum } = firewall;
  if (!vpcId || !flowProcessingCapacity || !protectionIpNum) {
    return;
  }
  isLoading.value = true;
  try {
    needMoreResource.value = await Firewall.checkNeedUpgradeResources({
      vpcId,
      flowProcessingCapacity,
      protectionIpNum,
    });
    if (needMoreResource.value) {
      return;
    }
    const updateOrderParams = getUpdateOrderParams();
    if (!updateOrderParams) {
      return;
    }
    if (isUpgrading.value) {
      const response = await Order.placeUpgradeOrder({ orders: [updateOrderParams] });
      Order.openOrderDetailPage(response.newOrderId);
    } else if (isDegrading.value) {
      const response = await Order.placeDegradeOrder({ orders: [updateOrderParams] });
      Order.openOrderDetailPage(response.newOrderId);
    }
  } finally {
    isLoading.value = false;
  }
};
</script>

<template>
  <SubViewContainer>
    <ElCard v-loading="isLoading">
      <ElForm label-width="150px" label-position="left">
        <ElFormItem :label="t('vpc')">
          <div>{{firewall.vpcId || ''}}({{firewall.vpcIp || ''}})</div>
        </ElFormItem>
        <ElFormItem :label="t('firewallName')">
          <div>{{firewall.firewallName ? firewall.firewallName : ''}}</div>
        </ElFormItem>
        <ElFormItem :label="t('versionSelect')">
          <div>{{t('advanceEdition')}}</div>
        </ElFormItem>
        <IpAndFlowCapacitySlider
          v-model:ipCount="firewall.protectionIpNum"
          v-model:flowCapacity="firewall.flowProcessingCapacity"
          :initValues="remoteValues"
          isUpdating
          @submit="onOrderResourceChange"
        />
      </ElForm>
      <div class="text-controller">
        <TotalPrice class="price-text" :price="price" :is-degrading="isDegrading" :is-loading="isQueryingPrice" />
        <div class="agreement-row">
          <ElCheckbox v-model="isCheckedAgree" :label="t('agreedToAgreement')" class="row-item" />
          <a>{{t('serviceAgreement')}}</a>
        </div>
        <div class="check-count-tip">
          {{needMoreResource ? t('needToCheckIpCountTip') : ''}}
        </div>
        <div class="fetch-order-failed-tip">
          {{isFailedToFetch ? t('fetchOrderFailedTip') + firewall.masterResourceId : ''}}
        </div>
        <div class="bottom-buttons-row">
          <ElButton
            type="primary"
            class="row-item"
            :disabled="isFailedToFetch || !isCheckedAgree"
            @click="onSubmit"
          >
            {{t('toChange')}}
          </ElButton>
          <RouterLink :to="{ name: 'configCenter.quota' }">
            <ElButton>{{t('toCancel')}}</ElButton>
          </RouterLink>
        </div>
      </div>
    </ElCard>
  </SubViewContainer>
</template>

<i18n lang="yaml" locale="zh-CN">
  vpc: '虚拟私有云'
  firewallName: '云防火墙名称'
  versionSelect: '版本选择'
  advanceEdition: '高级版'
  defenseIpCountStats: '可防护公网IP数'
  internetFlowProcessingCapacity: '公网流量处理能力'
  agreedToAgreement: '我已阅读并同意相关协议'
  serviceAgreement: '《天翼云云防火墙（原生版）服务协议》'
  needToCheckIpCountTip: '您所选择的“可防护公网IP数”数量小于正在防护的公网IP数，请先对不需要防护的IP关闭防护！'
  fetchOrderFailedTip: '获取订单详情失败，订单资源编号 '
  toChange: '立即变配'
  toCancel: '取消'
  noChangeBySlider: '变配内容未改变'
</i18n>

<style lang="scss" scoped>
.el-card {
  padding: 20px;
}

.guide-steps {
  margin-bottom: 16px;
}

:deep(.el-slider__marks-text) {
  white-space: nowrap;
}

.text-controller {
  display: flex;
  flex-direction: column;
  font-size: inherit;

  .price-text {
    margin-top: 140px;
    margin-bottom: 10px;
  }

  .check-count-tip,
  .fetch-order-failed-tip {
    height: 12px;
    margin-bottom: 20px;
    color: #f66;
  }

  .agreement-row,
  .bottom-buttons-row {
    display: flex;
    flex-direction: row;
    align-items: center;
    margin-bottom: 10px;

    .row-item {
      margin-right: 20px;
    }
  }
}

</style>
